#include "luat_base.h"
#include "luat_malloc.h"
#include "luat_msgbus.h"
#include "luat_timer.h"
#include "luat_gpio.h"

#include "rtthread.h"
#include <rtdevice.h>
/* 添加 fal 头文件 */
#include <fal.h>
/* 添加文件系统头文件 */
#include <dfs_fs.h>

#define DBG_TAG           "port.fs"
#define DBG_LVL           DBG_LOG
#include <rtdbg.h>

#include "drv_flash.h"
#include "lfs.h"

/* 定义要使用的分区名字 */
#define FS_PARTITION_NAME              "filesystem"

static uint8_t fs_ok = 0;

extern char luadb_inline[];

int luat_fs_init(void) {
    if (fs_ok) return 0;
    fs_ok = 1;
struct rt_device *mtd_dev = RT_NULL;
    /* 初始化 fal */
    fal_init();
    /* 生成 mtd 设备 */
    mtd_dev = fal_mtd_nor_device_create(FS_PARTITION_NAME);
    if (!mtd_dev)
    {
        LOG_E("Can't create a mtd device on '%s' partition.", FS_PARTITION_NAME);
    }
    else
    {
        /* 挂载 littlefs */
        if (dfs_mount(FS_PARTITION_NAME, "/", "lfs", 0, 0) == 0)
        {
            LOG_I("Filesystem initialized!");
        }
        else
        {
            /* 格式化文件系统 */
            dfs_mkfs("lfs", FS_PARTITION_NAME);
            /* 挂载 littlefs */
            if (dfs_mount("filesystem", "/", "lfs", 0, 0) == 0)
            {
                LOG_I("Filesystem initialized!");
            }
            else
            {
                LOG_E("Failed to initialize filesystem!");
            }
        }
    }
  // 尝试挂载luadb区域
    mkdir("/lua", 0);

    return 0;
}
INIT_ENV_EXPORT(luat_fs_init);
